package com.zealfi.wk.netty.server;

import com.zealfi.wk.netty.server.handler.inbound.MyServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.CompositeByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.concurrent.DefaultEventExecutorGroup;

/**
 * Created by kuan at 2018-03-20 下午 2:23
 */
public class MyServer {

    private final int port;

    public MyServer(int port) {
        this.port = port;
    }

    public void start() throws Exception {
        NioEventLoopGroup parentGroup = new NioEventLoopGroup();
        NioEventLoopGroup childGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(parentGroup,childGroup)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(port)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new ChannelInitializer<Channel>(){
                        @Override
                        protected void initChannel(Channel ch) {
                            ch.pipeline().addLast( //Channel与其互相绑定的ChannelPipeline，添加ChannelHandler列表
                                    new DefaultEventExecutorGroup(1), //开一个线程来执行ServerHandler
                                    new LineBasedFrameDecoder(1024),
                                    new StringDecoder(),
                                    new MyServerHandler());
                        }
                    });
            ChannelFuture future = bootstrap.bind().sync();

            System.out.println("MyServer start on port:"+port);

            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            childGroup.shutdownGracefully().sync();
            parentGroup.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws Exception {
        new MyServer(20000).start();
    }
}
